<template>
<div>
  <!--  面包屑导航-->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>商品管理</el-breadcrumb-item>
    <el-breadcrumb-item>分类参数</el-breadcrumb-item>
  </el-breadcrumb>
<!--  卡片视图区域-->
  <el-card>
<!--    警告框-->
    <el-alert show-icon title="注意：只允许为第三级分类设置相关参数" type="warning" :closable="false"></el-alert>
<!--    选中商品分类区域-->
    <el-row class="cat-opt">
      <el-col>
        <span>选择商品分类：</span>
<!--        选择商品的级联选择框-->
        <el-cascader
          expand-trigger='hover'
          v-model="selectCateKeys"
          :options="cateList"
          :props="cateProps"
          @change="handleChange"></el-cascader>
      </el-col>
    </el-row>
<!--tabs标签页-->
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="动态参数" name="many">
        <el-button type="primary" size="mini" :disabled="isBtnDisable" @click="showAddParamsDialogVisible">添加参数</el-button>
<!--        动态参数表格-->
        <el-table :data="manyTableData" border stripe>
          <el-table-column type="expand">
            <template slot-scope="scope">
<!--              循环渲染tag标签-->
              <el-tag @close="tagClose(i,scope.row)" closable v-for="(item,i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
<!--      input与tag切换显示-->
              <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(scope.row)"
              >+ New Tag</el-button>
            </template>
          </el-table-column>
          <el-table-column type="index"></el-table-column>
          <el-table-column label="参数名称" prop="attr_name"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showeditParamsDialogVisible(scope.row.attr_id)">编辑</el-button>
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="静态属性" name="only">
        <el-button type="primary" size="mini" :disabled="isBtnDisable" @click="showAddParamsDialogVisible">添加属性</el-button>
        <!--        静态属性表格-->
        <el-table :data="onlyTableData" border stripe>
          <el-table-column type="expand">
            <template slot-scope="scope">
              <!--              循环渲染tag标签-->
              <el-tag @close="tagClose(i,scope.row)" closable v-for="(item,i) in scope.row.attr_vals" :key="i">{{item}}</el-tag>
              <!--      input与tag切换显示-->
              <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(scope.row)"
              >+ New Tag</el-button>
            </template>
          </el-table-column>
          <el-table-column type="index"></el-table-column>
          <el-table-column label="属性名称" prop="attr_name"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showeditParamsDialogVisible(scope.row.attr_id)">编辑</el-button>
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </el-card>
<!--  添加参数-->
  <el-dialog
    :title="`添加${dialogTitle}`"
    :visible.sync="addParamsDialogVisible"
    width="70%"
    @close="addParamsClosed"
  >
    <el-form :model="addParams" :rules="addParamsRules" ref="addParamsRuleForm" label-width="100px">
      <el-form-item :label="dialogTitle" prop="attr_name">
        <el-input v-model="addParams.attr_name"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
    <el-button @click="addParamsDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addParam">确 定</el-button>
  </span>
  </el-dialog>
<!--  修改参数-->
  <el-dialog
    :title="`修改${dialogTitle}`"
    :visible.sync="editParamsDialogVisible"
    width="70%"
    @close="editParamsClosed"
  >
    <el-form :model="editParams" :rules="addParamsRules" ref="editParamsRuleForm" label-width="100px">
      <el-form-item :label="dialogTitle" prop="attr_name">
        <el-input v-model="editParams.attr_name"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
    <el-button @click="editParamsDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editParam">确 定</el-button>
  </span>
  </el-dialog>
</div>
</template>

<script>
export default {
  name: 'params',
  data () {
    return {
      cateList: [],
      // 级联选择框选中id
      selectCateKeys: [],
      // 级联选择框显示数据
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // tabs选择的name
      activeName: 'many',
      // 动态参数数据
      manyTableData: [],
      // 静态属性数据
      onlyTableData: [],
      // 添加分类对话框
      addParamsDialogVisible: false,
      // 修改分类对话框
      editParamsDialogVisible: false,
      // 添加参数
      addParams: {
        attr_name: ''
      },
      editParams: {
        attr_name: ''
      },
      // 添加分类验证规则
      addParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data } = await this.$axios.get('categories')
      if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
      this.cateList = data.data
    },
    // 级联选择框选择触发的函数
    handleChange () {
      this.getParamsData()
    },
    // 获取动态参数和静态属性
    async getParamsData () {
      // 只允许为第三级分类设置相关参数
      if (this.selectCateKeys.length !== 3) {
        // 代表没有选择三级分类
        this.selectCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return 0
      } else {
        const { data } = await this.$axios.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
        if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
        data.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          // input与tag标签切换显示
          // input的数据
          item.inputVisible = false
          item.inputValue = ''
        })
        console.log(data.data)
        if (this.activeName === 'many') {
          this.manyTableData = data.data
        } else {
          this.onlyTableData = data.data
        }
      }
    },
    // tabs标签选择触发
    handleTabClick () {
      this.getParamsData()
    },
    // 点击添加参数显示对话框
    showAddParamsDialogVisible () {
      this.addParamsDialogVisible = true
    },
    // 点击修改参数显示对话框
    async showeditParamsDialogVisible (id) {
      const { data } = await this.$axios.get(`categories/${this.cateId}/attributes/${id}`)
      if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
      this.editParams = data.data
      this.editParamsDialogVisible = true
    },
    // 监听添加对话框关闭事件
    addParamsClosed () {
      this.$refs.addParamsRuleForm.resetFields()
    },
    // 监听修改对话框关闭事件
    editParamsClosed () {
      this.$refs.editParamsRuleForm.resetFields()
    },
    // 添加参数
    addParam () {
      this.$refs.addParamsRuleForm.validate(async bool => {
        if (!bool) {
          this.addParamsDialogVisible = false
          return this.$message.error('表单预验证失败')
        }
        const { data } = await this.$axios.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParams.attr_name,
          attr_sel: this.activeName
        })
        if (data.meta.status !== 201) return this.$message.error(data.meta.msg)
        this.getParamsData()
        this.addParamsDialogVisible = false
        this.$message.success(data.meta.msg)
      })
    },
    // 修改参数
    editParam () {
      this.$refs.editParamsRuleForm.validate(async bool => {
        if (!bool) return this.$message.error('表单预验证失败')
        const { data } = await this.$axios.put(`categories/${this.cateId}/attributes/${this.editParams.attr_id}`, {
          attr_name: this.editParams.attr_name,
          attr_sel: this.activeName
        })
        if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
        this.$message.success(data.meta.msg)
        this.getParamsData()
        this.editParamsDialogVisible = false
      })
    },
    // 删除参数
    // eslint-disable-next-line camelcase
    removeParams (attr_id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // const { data } = await this.$axios.delete(`categories/${this.cateId}/attributes/${attr_id}`)
        // if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
        // this.$message.success(data.meta.msg)
        // this.getParamsData()
      }).catch(() => {
        this.$message.success('取消删除成功')
      })
    },
    //  input与tag切换显示键盘抬起与失去焦点触发函数
    handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return 0
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttrVals(row)
    },
    // 对tag进行参数添加与修改
    async saveAttrVals (row) {
      const { data } = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
      this.$message.success(data.meta.msg)
    },
    // 点击btn显示input标签
    showInput (row) {
      row.inputVisible = true
      // $nextTick方法的作用，就是当页面上元素被重新渲染之后，才会执行指定回调函数的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除标签
    tagClose (i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    }
  },
  computed: {
    isBtnDisable () {
      if (this.selectCateKeys.length !== 3) {
        return true
      }
      return false
    },
    cateId () {
      if (this.selectCateKeys.length === 3) {
        return this.selectCateKeys[2]
      }
      return null
    },
    dialogTitle () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style scoped>
.cat-opt{
margin:15px 0
}
.el-tag{
  margin-right: 10px;
}
.input-new-tag{
  width: 120px;
}
</style>
